package com.timmy.bluetooth.connect;

import android.os.Handler;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时操作类,类似于闹钟
 */
public class LoopTimer {
    private Timer mTimer;
    private TimerTask  mTask;
    private int period;
    private ILoopTimerListener listener;
    private Handler handler = new Handler();


    public LoopTimer(ILoopTimerListener listener, int periodms){
        this.listener = listener;
        this.period = periodms;
    }

    public void startTimer(){
        if(mTimer != null){
            stopTimer();
        }

        if(mTimer == null)
            mTimer = new Timer();

        //任务
        if(mTask == null){
            mTask = new TimerTask() {
                @Override
                public void run() {
                    listener.onLoopTimer();
                }
            };
        }

        mTimer.schedule(mTask,period,period);
    }

    public boolean isTimering(){
        if(mTimer != null){
            return true;
        }else{
            return false;
        }
    }

    public void stopTimer(){
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }

        if(mTask != null){
            mTask.cancel();
            mTask = null;
        }
    }
}
